package modelz;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;


public abstract class Updateable<T extends Updateable<T>> {

	private final List<UpdateListener<T>> listeners = new CopyOnWriteArrayList<UpdateListener<T>>();

	@SuppressWarnings("unchecked")
	public void update() {
		for (UpdateListener<T> listener : new ArrayList<UpdateListener<T>>(
				listeners))
			listener.updated((T) this);
	}

	public void addListener(UpdateListener<T> listener) {
		addListener(listener, true);
	}

	@SuppressWarnings("unchecked")
	public void addListener(UpdateListener<T> listener, boolean catchUp) {
		listeners.add(listener);
		if( catchUp )
			listener.updated((T)this);
	}

	public void removeListener(UpdateListener<T> listener) {
		listeners.remove(listener);
	}

}
